import React, { Component } from "react";
import { Form, Input, Button } from 'antd';
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import logo from "../../static/imgs/logo.png";
import "./css/login.less";
//input上带的图标
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { saveUserinfo } from "../../redux/actions/login_action";
import { reqLogin } from "../../api";
const { Item } = Form;

@connect(
    state => ({ isLogin: state.userInfo.isLogin }),
    {
        saveUserinfo: saveUserinfo,
    })
class Login extends Component {

    /**
     * 密码验证 ，如果有异步（类似网络请求）的处理可以使用此方法，
     * 如果没有这种需求只需提示，直接用普通rule的属性就可以了
     * @param {*} _ 
     * @param {*} value 用户在input中输入的值 
     * @returns 
     */
    pwdValidator = (_, value) => {
        if (!value)
            return Promise.reject("密码必须输入")
        else if (value.length > 12 || value.length < 4) {
            return Promise.reject("密码4-12位")
        } else if (!(/^\w+$/).test(value)) {
            return Promise.reject("密码必须是字母、数字、下划线组成")
        } else {
            return Promise.resolve()
        }
    }

    /**
     * 提交的回调
     * @param {提交的值对象} value 
     */
    onFinish = async (value) => {
        let { username, password } = value;
        // reqLogin(username, password)
        //     .then((v) => {
        //         console.log(v)
        //     })
        //     .catch(reason => {
        //         console.log(reason);
        //     });
        let result = await reqLogin(username, password);
        this.props.saveUserinfo(result);
        this.props.history.replace("/admin/home");
    }

    /**
     * 提交的失败回调，没有通过input rule规则，返回的错误就到这个回调里
     * @param {错误对象} error 
     */
    onFinishFailed = (error) => {
        alert("请检查用户名和密码")
    }

    render() {
        if (this.props.isLogin)
            return <Redirect to="/admin/home" />
        return (
            <div className="login">
                <header>
                    <img src={logo} alt="" />
                    <h1>商品管理系统</h1>
                </header>
                <section>
                    <h1>用户登录</h1>
                    <Form name="horizontal_login" onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
                        <Item
                            name="username"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入用户名',
                                },
                                {
                                    max: 12,
                                    min: 4,
                                    message: "用户名4-12位"
                                },
                                {
                                    pattern: /^\w+$/,
                                    message: "用户名是字母、数字、下划线组成"
                                }
                            ]}
                        >
                            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
                        </Item>
                        <Item
                            name="password"
                            rules={[
                                { validator: this.pwdValidator }
                            ]}
                        >
                            <Input
                                prefix={<LockOutlined className="site-form-item-icon" />}
                                type="password"
                                placeholder="密码"
                            />
                        </Item>
                        <Item>
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="login-form-button"
                            >
                                登录
                            </Button>
                        </Item>
                    </Form>
                </section>
            </div>
        )
    }
}

export default Login;